package com.example.letgo.trip;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.letgo.Fragment.PersoncenterFragment;
import com.example.letgo.R;
import com.example.letgo.global.Constant;
import com.example.letgo.model.Team;
import com.example.letgo.story.StoryReleaseActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;
import java.io.Serializable;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.DatePicker;
import cn.addapp.pickers.picker.DateTimePicker;
import cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;
import okhttp3.Response;

public class TripReleaseActivity extends AppCompatActivity {
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    @BindView(R.id.release)
    TextView release;
    @BindView(R.id.imageView)
    ImageView imageView;
    /**
     * 获取到的图片路径
     */
    private String picPath;
    private Uri photoUri;
    @BindView(R.id.Trip_return_person)
    ImageView TripReturnPerson;
    @BindView(R.id.startPlace)
    TextView startPlace;
    @BindView(R.id.startPlace_choose)
    RelativeLayout startPlaceChoose;
    @BindView(R.id.endPlace)
    TextView endPlace;
    @BindView(R.id.endPlace_choose)
    RelativeLayout endPlaceChoose;
    @BindView(R.id.add_content)
    EditText addContent;
    @BindView(R.id.endGroupTime)
    TextView endGroupTime;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.endGroupTime_choose)
    RelativeLayout endGroupTimeChoose;
    @BindView(R.id.begin_Time)
    TextView beginTime;
    @BindView(R.id.beginTime_choose)
    RelativeLayout beginTimeChoose;
    @BindView(R.id.end_Time)
    TextView endTime;
    @BindView(R.id.endTime_choose)
    RelativeLayout endTimeChoose;
    @BindView(R.id.Money)
    TextView Money;
    @BindView(R.id.Money_choose)
    RelativeLayout MoneyChoose;
    @BindView(R.id.rb_Male)
    RadioButton rbMale;
    @BindView(R.id.rb_FeMale)
    RadioButton rbFeMale;
    @BindView(R.id.rb_No)
    RadioButton rbNo;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;
    @BindView(R.id.Team_person)
    EditText TeamPerson;
    @BindView(R.id.Img_Tihuan)
    ImageView ImgTihuan;
    @BindView(R.id.Img_choose)
    ImageView ImgChoose;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trip_release);
        ButterKnife.bind(this);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.Trip_return_person, R.id.startPlace_choose, R.id.endPlace_choose, R.id.endGroupTime_choose, R.id.beginTime_choose, R.id.endTime_choose, R.id.Money_choose, R.id.Img_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Trip_return_person:
                finish();
                break;
            case R.id.startPlace_choose:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    selectAddress(startPlace);//调用CityPicker选取区域
                }
                break;
            case R.id.endPlace_choose:
                InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm1.isActive()) {
                    imm1.hideSoftInputFromWindow(view.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    selectAddress(endPlace);//调用CityPicker选取区域
                }
                break;
            case R.id.endGroupTime_choose:
                DateTimePicker picker = new DateTimePicker(this, DateTimePicker.HOUR_24);
                picker.setDateRangeStart(2017, 1, 1);
                picker.setDateRangeEnd(2025, 11, 11);

                picker.setSelectedItem(2018, 6, 16, 16, 43);
                picker.setTimeRangeStart(9, 0);
                picker.setTimeRangeEnd(20, 30);
                picker.setWeightEnable(true);
                picker.setWheelModeEnable(true);
                LineConfig config = new LineConfig();
                config.setColor(Color.BLUE);//线颜色
                config.setAlpha(120);//线透明度
                config.setVisible(false);//线不显示 默认显示
                picker.setLineConfig(config);
                picker.setOnDateTimePickListener(new DateTimePicker.OnYearMonthDayTimePickListener() {
                    @Override
                    public void onDateTimePicked(String year, String month, String day, String hour, String minute) {
                        endGroupTime.setText(year + "-" + month + "-" + day + " " + hour + ":" + minute);
                    }
                });
                picker.show();
                break;
            case R.id.beginTime_choose:
                final DatePicker picker1 = new DatePicker(this);
                picker1.setCanLoop(true);
                picker1.setWheelModeEnable(true);
                picker1.setTopPadding(15);
                picker1.setRangeStart(2016, 8, 29);
                picker1.setRangeEnd(2111, 1, 11);
                picker1.setSelectedItem(2050, 10, 14);
                picker1.setWeightEnable(true);
                picker1.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        beginTime.setText(year + "-" + month + "-" + day);
                    }
                });
                picker1.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker1.setTitleText(year + "-" + picker1.getSelectedMonth() + "-" + picker1.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker1.setTitleText(picker1.getSelectedYear() + "-" + month + "-" + picker1.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker1.setTitleText(picker1.getSelectedYear() + "-" + picker1.getSelectedMonth() + "-" + day);
                    }
                });
                picker1.show();
                break;
            case R.id.endTime_choose:
                final DatePicker picker2 = new DatePicker(this);
                picker2.setCanLoop(true);
                picker2.setWheelModeEnable(true);
                picker2.setTopPadding(15);
                picker2.setRangeStart(2016, 8, 29);
                picker2.setRangeEnd(2111, 1, 11);
                picker2.setSelectedItem(2050, 10, 14);
                picker2.setWeightEnable(true);
                picker2.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        endTime.setText(year + "-" + month + "-" + day);
                    }
                });
                picker2.setOnWheelListener(new DatePicker.OnWheelListener() {
                    @Override
                    public void onYearWheeled(int index, String year) {
                        picker2.setTitleText(year + "-" + picker2.getSelectedMonth() + "-" + picker2.getSelectedDay());
                    }

                    @Override
                    public void onMonthWheeled(int index, String month) {
                        picker2.setTitleText(picker2.getSelectedYear() + "-" + month + "-" + picker2.getSelectedDay());
                    }

                    @Override
                    public void onDayWheeled(int index, String day) {
                        picker2.setTitleText(picker2.getSelectedYear() + "-" + picker2.getSelectedMonth() + "-" + day);
                    }
                });
                picker2.show();
                break;
            case R.id.Money_choose:
                boolean isChinese = Locale.getDefault().getDisplayLanguage().contains("中文");
                SinglePicker<String> pickerP = new SinglePicker<>(this,
                        isChinese ? new String[]{
                                "100-300", "300-500", "500-700", "700-900", "900-1000", "100-1500",
                                "1500-2000", "2000-3000", "3000-4000", "4000+"
                        } : new String[]{
                                "100-300", "300-500", "500-700", "700-900", "900-1000", "100-1500",
                                "1500-2000", "2000-3000", "3000-4000", "4000+"
                        });
                pickerP.setCanLoop(false);//不禁用循环
                pickerP.setTopBackgroundColor(0xFFEEEEEE);
                pickerP.setTopHeight(50);
                pickerP.setTopLineColor(0xFF33B5E5);
                pickerP.setTopLineHeight(1);
                pickerP.setTitleText(isChinese ? "请选择" : "Please pick");
                pickerP.setTitleTextColor(0xFF999999);
                pickerP.setTitleTextSize(12);
                pickerP.setCancelTextColor(0xFF33B5E5);
                pickerP.setCancelTextSize(13);
                pickerP.setSubmitTextColor(0xFF33B5E5);
                pickerP.setSubmitTextSize(13);
                pickerP.setSelectedTextColor(0xFFEE0000);
                pickerP.setUnSelectedTextColor(0xFF999999);
                pickerP.setWheelModeEnable(true);
                LineConfig configP = new LineConfig();
                configP.setColor(Color.BLUE);//线颜色
                configP.setAlpha(120);//线透明度
                pickerP.setLineConfig(configP);
                pickerP.setItemWidth(200);
                pickerP.setBackgroundColor(0xFFE1E1E1);
                //picker.setSelectedItem(isChinese ? "处女座" : "Virgo");
                pickerP.setSelectedIndex(7);
                pickerP.setOnItemPickListener(new OnItemPickListener<String>() {
                    @Override
                    public void onItemPicked(int index, String item) {
                        Money.setText(item);
                    }
                });
                pickerP.show();
                break;
            case R.id.Img_choose:

                Intent intentI = new Intent();
                intentI.setType("image/*");
                intentI.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intentI, SELECT_PIC_BY_PICK_PHOTO);
                break;
        }
    }

    private void selectAddress(final TextView textView) {
        CityPicker cityPicker = new CityPicker.Builder(TripReleaseActivity.this)
                .textSize(14)
                .title("地址选择")
                .titleBackgroundColor("#FFFFFF")
                .confirTextColor("#696969")
                .cancelTextColor("#696969")
                .province("江苏省")
                .city("常州市")
                .district("天宁区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //邮编
                String code = citySelected[3];
                //为TextView赋值
                textView.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
    private void doPhoto(int requestCode, Intent data) {
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) //从相册取图片，有些手机有异常情况，请注意
        {
            if (data == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
            photoUri = data.getData();
            if (photoUri == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.e(">>>>>>>", "imagePath = " + picPath);

        if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
            ImgTihuan.setImageURI(Uri.fromFile(new File(picPath)));
        } else {
            Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
        }
    }

    @OnClick(R.id.release)
    public void onViewClicked() {
        addContent.getText();
        if (((RadioButton) TripReleaseActivity.this.findViewById(rgSex.getCheckedRadioButtonId())).getText() == null){
            showToast("请完善数据!");
        }
        if (startPlace.getText() != null && endPlace.getText() != null && addContent.getText() != null &&
                endGroupTime.getText() != null && beginTime.getText() != null && endTime.getText() != null &&
                Money.getText() != null && ((RadioButton) TripReleaseActivity.this.findViewById(rgSex.getCheckedRadioButtonId())).getText() != null &&
                TeamPerson.getText() != null && ImgTihuan.getDrawable() != null) {
            int userId = Constant.id;
            Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
            t.setToNow(); // 取得系统时间。
            int year = t.year;
            int month = t.month;
            int day = t.monthDay;
            int hour = t.hour; // 0-23
            int minute = t.minute;
            String startTime = year + "-" + month + "-" + day + "-" + hour + ":" + minute;
            ImgTihuan.setDrawingCacheEnabled(true);
            Bitmap obmp = Bitmap.createBitmap(ImgTihuan.getDrawingCache());  //获取到Bitmap的图片
            ImgTihuan.setDrawingCacheEnabled(false);
            final Team team = new Team();
            team.setTeamUserId(userId);
            team.setTeamStartPlace(startPlace.getText().toString());
            team.setTeamOverPlace(endPlace.getText().toString());
            team.setTeamText(addContent.getText().toString());
            team.setTeamTime(startTime);
            team.setTeamOverTime(endGroupTime.getText().toString());
            team.setTeamDate(beginTime.getText().toString() + "-" + endTime.getText().toString());
            team.setTeamMoney(Money.getText().toString());
            team.setTeamSex(((RadioButton) TripReleaseActivity.this.findViewById(rgSex.getCheckedRadioButtonId())).getText().toString());
            team.setTeamImage(picPath);
            team.setTeamPersons(TeamPerson.getText().toString());

            File file = new File(picPath);
            OkGo.post("http://119.29.113.114:8080/gogogo/team/add")
                    .params("teamDate",beginTime.getText().toString() + "-" + endTime.getText().toString())
                    .params("teamImageFile", file)
                    .params("teamMoney", Money.getText().toString())
                    .params("teamOverPlace", endPlace.getText().toString())
                    .params("teamOverTime", endGroupTime.getText().toString())
                    .params("teamPersons",TeamPerson.getText().toString())
                    .params("teamSex",((RadioButton) TripReleaseActivity.this.findViewById(rgSex.getCheckedRadioButtonId())).getText().toString())
                    .params("teamStartPlace", startPlace.getText().toString())
                    .params("teamText", addContent.getText().toString())
                    .params("teamTime",startTime)
                    .params("teamUserId", userId)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            //跳转页面
                            if (response.code() == 200) {
                                Intent intent = new Intent(TripReleaseActivity.this,TripReleaseSuccess.class);
                                intent.putExtra("team", new Gson().toJson(team));
                                startActivity(intent);
                                finish();
                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            Log.e("error:", String.valueOf(e));
                            showToast("失败，服务端异常");
                        }
                    });


        }else {
            showToast("请完善数据!");
        }
    }

}
